<template>
    <div class="fireDetail">
        <div class="header">
            <span
                :class="{text:true, textActive:currentIndex==index}"
                v-for="(item, index) of titleName"
                @click="handleHeaderCilck(index)"
                :key="item"
                >{{item.name}}</span
            >
            <span class="close" @click="closeDetail()">
                <i class="el-icon-close"></i>
            </span>
        </div>
        <div v-show="isDetailPanel">
            <div class="infoBox" v-if="detailData">
                <div class="infoItem">
                    <p>
                        <span>时间:</span>
                        <span>{{ detailData.observeTime }}</span>
                    </p>
                </div>
                <div class="infoItem">
                    <p>
                        <span>地名:</span>
                        <span>{{ detailData.cityRegion }}</span>
                    </p>
                </div>
                <div class="infoItem">
                    <p>
                        <span>强度:</span>
                        <span>{{ detailData.intensityG || "未知" }}</span>
                    </p>
                </div>
                <div class="infoItem">
                    <p>
                        <span>下垫面类型:</span>
                        <span>{{ detailData.vegType }}</span>
                    </p>
                </div>
                <div class="infoItem">
                    <p>
                        <span>距离:</span>
                        <span>{{ detailData.distance }}</span>
                    </p>
                </div>
                <div class="infoItem">
                    <p>
                        <span>方位角:</span>
                        <span>{{ detailData.direction }}</span>
                    </p>
                </div>
                <div class="infoItem">
                    <p>
                        <span>高程:</span>
                        <span>{{ detailData.elevationAver || "未知" }}</span>
                    </p>
                </div>
                <div class="infoItem">
                    <p>
                        <span>经度:</span>
                        <span>{{ detailData.longitude.toFixed(7) }}</span>
                    </p>
                    <p>
                        <span>纬度:</span>
                        <span>{{ detailData.latitude.toFixed(7) }}</span>
                    </p>
                </div>
                <div class="infoItem">
                    <p>
                        <span>行政编码:</span>
                        <span>{{ detailData.adminCode }}</span>
                    </p>
                </div>
                <div class="infoItem">
                    <p>
                        <span>疑似重复次数:</span>
                        <span>{{ detailData.repeat }}</span>
                    </p>
                </div>
            </div>
            <div class="typeBox" v-if="detailData && detailData.gfAver">
                <div class="typeItem">
                    <p>
                        <span>植被类型:</span>
                        <span>{{ detailData.speciesType }}</span>
                    </p>
                </div>
                <div class="typeItem">
                    <p>
                        <span>植被覆盖度(平均):</span>
                        <span>{{
                            detailData.gfAver ? detailData.gfAver + "%" : 0
                        }}</span>
                    </p>
                </div>
                <div class="typeItem">
                    <p>
                        <span>森林:</span>
                        <span>{{
                            detailData.forestPercent
                                ? detailData.forestPercent + "%"
                                : 0
                        }}</span>
                    </p>
                    <p>
                        <span>草地:</span>
                        <span>{{
                            detailData.lawnPercent
                                ? detailData.lawnPercent + "%"
                                : 0
                        }}</span>
                    </p>
                </div>
                <div class="typeItem">
                    <p>
                        <span>农田及自然植被:</span>
                        <span>{{
                            detailData.farm ? detailData.farm + "%" : 0
                        }}</span>
                    </p>
                    <p>
                        <span>灌木:</span>
                        <span>{{
                            detailData.bush ? detailData.bush + "%" : 0
                        }}</span>
                    </p>
                </div>
                <div class="typeItem">
                    <p>
                        <span>城市或荒漠:</span>
                        <span>{{
                            detailData.city ? detailData.city + "%" : 0
                        }}</span>
                    </p>
                </div>
            </div>
        </div>
        <div class="" v-show="!isDetailPanel">
            <div class="infoBox" style="margin-top:20px;">
                <el-input-number v-model="radius" size="small" controls-position="right" @change="selectChange" :min="1" ></el-input-number>
                <!-- <el-select v-model="radius" 
                @change="selectChange"
                placeholder="请选择距离"> 
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select> -->
                <div v-for="(item,index) in ziyuanList" :key="index">
                    {{item}}
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import axios from "axios";
import { keyFormate } from "./dictionary.js";
let circleEntity = []; //扩散波
let poiModel = []; //poi点
export default {
    name: "fireDetail",
    data() {
        return {
            detailData: null,
            titleName: [
                {
                    name: "火点监测信息",
                },
                {
                    name: "周边应急资源信息",
                },
            ],
            options: [
                {
                    value: 3,
                    label: '三公里'
                }, {
                    value: 5,
                    label: '五公里'
                }, {
                    value: 10,
                    label: '十公里'
                }, {
                    value: 15,
                    label: '十五公里'
                }
            ],
            ziyuanList:[],
            currentIndex:0,
            isDetailPanel: true,
            radius: 3, //扩散波半径km
            cityCenter: {
                海口市: [110.198418, 20.045805],
                三亚市: [109.511709, 18.252865],
                三沙市: [112.234483, 16.774644],
                儋州市: [109.580812, 19.520948],
                五指山市: [109.516784, 18.774827],
                文昌市: [110.797473, 19.544234],
                琼海市: [110.474524, 19.259112],
                万宁市: [110.392605, 18.793697],
                东方市: [108.651829, 19.095187],
                定安县: [110.358001, 19.681215],
                屯昌县: [110.101667, 19.351662],
                澄迈县: [110.007497, 19.738885],
                临高县: [109.690508, 19.912025],
                白沙黎族自治县: [109.4429, 19.221641],
                昌江黎族自治县: [109.055783, 19.298139],
                乐东黎族自治县: [109.173384, 18.750063],
                陵水黎族自治县: [110.037553, 18.506045],
                保亭黎族苗族自治县: [109.700373, 18.640156],
                琼中黎族苗族自治县: [109.838389, 19.033369],
            },
        };
    },
    props: ["fireId"],
    watch: {
        fireId(val) {
            this.getFireData();
        },
    },
    mounted() {
        // 获取火点详情
        this.getFireData();
    },
    methods: {
        handleHeaderCilck(index) {
            console.log(index)
            this.currentIndex = index
            this.isDetailPanel = !this.isDetailPanel
        },
        selectChange(val){
            this.showCricle()
            this.$store.commit("changeCircleRadius",val)
        },
        // 关闭面板
        closeDetail() {
            this.$emit("closeDetail");
        },
        // 获取火点详情
        async getFireData() {
            let res = await axios.get(
                `${window.huoqingApiUrl}/task/firePointDetail`,
                { params: { id: this.fireId } }
            );
            let cityLonLat = this.cityCenter[res.data.cityRegion];
            res.data.distance =
                this.calcDistance(cityLonLat, [
                    res.data.longitude,
                    res.data.latitude,
                ]).toFixed(3) + "Km";
            res.data.direction = this.calcAngle(cityLonLat, [
                res.data.longitude,
                res.data.latitude,
            ]);

            // var positions = [
            //   Cesium.Cartographic.fromDegrees(res.data.longitude, res.data.latitude)    //输入经纬度
            // ];
            // var promise = Cesium.sampleTerrain(window.dx,positions);
            // Cesium.when(promise, function (updatedPositions) {
            //   var terrainHeight = updatedPositions[0].height;
            //   console.log(terrainHeight)
            //   res.data.elevationAver = terrainHeight
            // });

            // res.data.elevationAver = h1
            this.detailData = res.data;
            // 添加扩散波
            this.showCricle();
        },
        // 计算距离
        calcDistance(p1, p2) {
            const distance = turf.distance(turf.point(p1), turf.point(p2), {
                units: "kilometers",
            }); //转换单位 米
            return distance;
        },
        calcAngle(p1, p2) {
            let describe = "0";
            let num = "0";
            let angle = turf.bearing(p1, p2).toFixed(3);
            angle = parseInt(angle);
            if (angle > 0 && angle < 90) {
                describe = "北偏东";
                num = angle;
            } else if (angle > 90 && angle < 180) {
                describe = "东偏南";
                num = angle - 90;
            } else if (angle < 0 && angle > -90) {
                describe = "北偏西";
                num = Math.abs(angle);
            } else if (angle < -90 && angle > -180) {
                describe = "西偏南";
                num = Math.abs(angle + 90);
            }
            return `${describe}${num}°`;
        },
        // 扩散波
        showCricle() {
            if (circleEntity) this.hideCircle();
            // if(this.radius <= 0) return;
            let data = {
                id: this.detailData.id,
                imageUrl: "/images/fireReport/ripple.png",
                lon: this.detailData.longitude,
                lat: this.detailData.latitude,
                height: 0,
                minR: 100,
                maxR: this.radius * 1000,
                deviationR: this.radius * 10,
            };
            let r1 = data.minR,
                r2 = data.minR;
            function changeR1() {
                r1 = r1 + data.deviationR;
                if (r1 >= data.maxR) {
                    r1 = data.minR;
                }
                return r1;
            }
            function changeR2() {
                return r1;
            }
            circleEntity = viewer.entities.add({
                name: "",
                // id: data.id,
                position: Cesium.Cartesian3.fromDegrees(
                    data.lon,
                    data.lat,
                    data.height
                ),
                ellipse: {
                    semiMinorAxis: data.maxR,
                    semiMajorAxis: data.maxR,
                    // semiMinorAxis: new Cesium.CallbackProperty(changeR2,false),
                    // semiMajorAxis: new Cesium.CallbackProperty(changeR1,false),
                    height: data.height,
                    material: new Cesium.ImageMaterialProperty({
                        // image: data.imageUrl,
                        repeat: new Cesium.Cartesian2(1.0, 1.0),
                        transparent: true,
                        color: Cesium.Color.RED.withAlpha(0.2),
                        // color: new Cesium.CallbackProperty(function () {
                        //   return Cesium.Color.WHITE.withAlpha(1.7-r1/data.maxR)  //entity的颜色透明 并不影响材质，并且 entity也会透明哦
                        // },false)
                    }),
                },
            });
            // 添加poi点
            this.showPOI(data, "leftClick", this.handlePointClick);
        },
        handlePointClick(entity) {
            axios
                .get(`${sjzxUrl}/api/poi-point/getInfo/${entity.id}`)
                .then((res) => { 
                    console.log(res.data);
                    let poiDetail = keyFormate(entity.name, res.data);
                    poiDetail["poiNAME"] = entity.name;
                    this.$store.commit("changeInfoBoxContent", poiDetail);
                    this.addBoundInfoBox(entity.position._value, "infoBox6");
                });
        },
        addBoundInfoBox(positionValue, elementId) {
            const oneDiv = window.document.getElementById(elementId);
            oneDiv.style.display = "block";
            let preRenderListener = viewer.scene.postRender.addEventListener(
                function () {
                    let elWidth = oneDiv.offsetWidth;
                    let elHeight = oneDiv.offsetHeight; // + 60
                    const scratch = new Cesium.Cartesian2(); //cesium二维笛卡尔 笛卡尔二维坐标系就是我们熟知的而二维坐标系；三维也如此
                    var cartographicPosition =
                        Cesium.Ellipsoid.WGS84.cartesianToCartographic(
                            positionValue
                        ); //笛卡尔转84
                    var lat = Cesium.Math.toDegrees(
                        cartographicPosition.latitude
                    );
                    var lng = Cesium.Math.toDegrees(
                        cartographicPosition.longitude
                    );
                    var cart = new Cesium.Cartographic.fromDegrees(lng, lat); //输入经纬度
                    var h = viewer.scene.sampleHeight(cart);
                    // var promise = Cesium.sampleTerrainMostDetailed(window.dx, positions);//(地形数据，positions)
                    var positionFinal = Cesium.Cartesian3.fromDegrees(lng, lat, h); //加入高度之后，不会飘，但是不能解决地球缩放问题
                    const canvasPosition =
                        viewer.scene.cartesianToCanvasCoordinates(
                            positionFinal,
                            scratch
                        ); //cartesianToCanvasCoordinates 笛卡尔坐标（3维度）到画布坐标

                    if (Cesium.defined(canvasPosition)) {
                        // 根据元素宽高及当前点屏幕坐标进行偏移
                        oneDiv.style.top =
                            canvasPosition.y - elHeight * 1.1 + "px";
                        oneDiv.style.left =
                            canvasPosition.x - elWidth / 2 + "px";
                    }
                }
            );
        },
        // 清除扩散波
        hideCircle() {
            viewer.entities.remove(circleEntity);
            circleEntity = null;
        },
        // 渲染POI点
        async showPOI(data, eventType, event) {
            let params = { lon: data.lon, lat: data.lat, radius: data.maxR };
            let poiRes = await axios.get(
                `${window.huoqingApiUrl}/api/poi-point/nearby`,
                { params: params }
            );
            // this.selectOptions = poiRes
            // 每次更新数据，清除之前的实体
            this.hidePOI();
            poiModel = [];
            //添加标记
            for (let item of poiRes.data) {
                let entity = viewer.entities.add({
                    name: item.ppType,
                    id: item.ppId,
                    position: Cesium.Cartesian3.fromDegrees(
                        item.ppLon,
                        item.ppLat
                    ),
                    billboard: {
                        image: `./images/fireReport/poi/${item.ppGroup}_${item.ppType}.png`,
                        scale: 0.8,
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        scaleByDistance: new Cesium.NearFarScalar(
                            10000,
                            1,
                            100000,
                            0.7
                        ),
                        disableDepthTestDistance: Number.POSITIVE_INFINITY,
                        width: 30,
                        height: 30,
                    },
                    entityType: "poi",
                    poiType: item.ppType,
                });
                if (eventType && event) {
                    entity[eventType] = event;
                }
                poiModel.push(entity);
            }
            // this.poiFormated = this.calPoiNum(poiRes)
            // console.log(this.poiFormated)
        },
        // 清除POI点
        hidePOI() {
            for (var i = 0; i < poiModel.length; i++) {
                viewer.entities.remove(poiModel[i]);
            }
            poiModel = [];
        },
    },
    beforeUnmount() {
        this.hideCircle();
        this.hidePOI();
        // if(handler3D){
        //   handler3D.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
        //   handler3D = null;
        // }
    },
};
</script>
<style  lang="stylus" >
.el-input-number__decrease, .el-input-number__increase {
    height: 14px !important;
    line-height: 14px !important;
    width: 19px;
    background: rgba(14,103,160,0.2);
    border: 0px solid #5082b2 !important;
    border-radius: 0;
}
.el-input-number__decrease {
    border-top: none !important;
}

.el-icon-arrow-down {
    color: #fff;
    line-height: 1.3;
}
.el-input__inner {
    height: 28px;
    line-height: 28px;
    padding-left: 10px;
    padding-right: 10px;
    background: rgba(60, 97, 133, 0.2);
    border: 1px solid #5082b2;
    font-size: 16px;
    color: #cde6ff;
    border-radius: 2px;
    padding: 0 10px;
    text-align: left;
}
</style>
<style lang="stylus" scoped>
.fireDetail {
    position: fixed;
    top: vh(100);
    right: vw(450);
    width: 300px;
    max-height: 500px;
    padding: 10px;
    background: rgba(0, 0, 0, 0.5);

    .header {
        display: flex;
        justify-content: space-between;

        .text {
            color: #fff;
            font-size: 18px;
        }
        .text.textActive{
            color: #00e5fd;
            border-bottom:1px solid #00e5fd;
            padding-bottom:5px;
        }

        .close {
            cursor: pointer;
        }
    }

    .infoBox, .typeBox {
        padding-bottom: 10px;
        border-bottom: 2px dotted #0c4f55;

        .infoItem, .typeItem {
            display: flex;
            justify-content: space-between;

            p {
                line-height: 30px;
                color: #fff;
                font-size: 14px;

                span:first-child {
                    color: rgba(109, 204, 188, 1);
                    margin-right: 5px;
                }
            }
        }
    }

    .typeBox {
        border-bottom: 0;
    }
}
</style>